package com.jevons.muffin.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ViewSwitcher;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import com.jevons.muffin.R;
import com.jevons.muffin.activity.BaseView;
import com.jevons.muffin.event.BaseActionEvent;
import com.jevons.muffin.event.FinishActivityEvent;
import com.jevons.muffin.event.LoadingDialogEvent;
import com.jevons.muffin.event.StartActivityEvent;
import com.jevons.muffin.event.ToastEvent;
import com.jevons.muffin.vm.BasePresenter;
import com.jevons.muffin.vm.IViewModelAction;
import com.trello.rxlifecycle3.LifecycleTransformer;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Fragment 基类
 * @author linaisheng
 * Created at 2019/3/29.
 */

public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseView {


    /**
     * 作为fragment载体的activity
     */
    protected Activity parentActivity;

    protected P presenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewModelEvent();
        presenter = initPresenter();
        //绑定View
        if (presenter != null) {
            presenter.attachView(this);
        }
    }

    //初始化Presenter
    protected abstract P initPresenter();

    protected abstract ViewModel initViewModel();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //默认布局
        ViewSwitcher parent = (ViewSwitcher) inflate(R.layout.fragment_base_layout);
        parent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        //自定义布局
        int resource = getContentView();
        if (resource > 0) {
            ViewGroup.LayoutParams viewGroup = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            parent.addView(inflater.inflate(resource, null), viewGroup);
        }
        parent.setDisplayedChild(1);

        return parent;
    }

    @Override
    public final void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onInitView(savedInstanceState);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // fragment载体的Activity
        this.parentActivity = (Activity) context;
    }

    @Override
    public void onDestroyView() {
        if (presenter != null) {
            presenter.detachView();
        }
        super.onDestroyView();

    }

    /**
     * 加载布局文件
     *
     * @return int 布局文件
     */
    public abstract int getContentView();

    /**
     * 初始化数据
     */
    public abstract void onInitView(Bundle savedInstanceState);

    /**
     * findViewById
     *
     * @param resId 资源id
     * @return view
     */
    protected final View findViewById(int resId) {
        return getView().findViewById(resId);
    }

    /**
     * 加载布局
     *
     * @param resource 资源文件
     * @return View
     */
    protected View inflate(int resource) {
        return LayoutInflater.from(parentActivity).inflate(resource, null);
    }

    @Override
    public LifecycleTransformer bindToLifecycle() {
        if (parentActivity instanceof BaseView) {
            return ((BaseView) parentActivity).bindToLifecycle();
        }
        return null;
    }

    private void initViewModelEvent() {
        ViewModel viewModel = initViewModel();
        if (viewModel != null) {
            List<ViewModel> modelList = new ArrayList<>();
            modelList.add(viewModel);
            if (isObserveEventViewModel()) {
                observeEvent(modelList);
            }
        }
    }

    protected boolean isObserveEventViewModel() {
        return true;
    }

    private void observeEvent(List<ViewModel> viewModelList) {
        for (ViewModel viewModel : viewModelList) {
            if (viewModel instanceof IViewModelAction) {
                IViewModelAction viewModelAction = (IViewModelAction) viewModel;
                viewModelAction.getActionLiveData().observe(
                        this, new Observer<BaseActionEvent>() {
                            @Override
                            public void onChanged(BaseActionEvent baseActionEvent) {
                                if (baseActionEvent != null) {
                                    handleActionEvent(baseActionEvent);
                                }
                            }
                        });
            }
        }
    }

    protected void handleActionEvent(BaseActionEvent actionEvent) {
        Object data = actionEvent.getData();
        //加载框事件
        if (data instanceof LoadingDialogEvent) {
            LoadingDialogEvent event = (LoadingDialogEvent) data;
            if (event.isShowing()) {
                String msg = event.getMessage();
                if (TextUtils.isEmpty(msg)) {
                    showLoading();
                } else {
                    showLoading(msg);
                }
            } else {
                hideLoading();
            }
        }
        //toast事件
        else if (data instanceof ToastEvent) {
            ToastEvent event = (ToastEvent) data;
            showToast(event.getMessage());
        }
        //结束activity事件
        else if (data instanceof FinishActivityEvent) {
            FinishActivityEvent event = (FinishActivityEvent) data;
            if (event.hasResultCode()) {
                if (event.getData() != null) {
                    getActivity().setResult(event.getResultCode(), event.getData());
                } else {
                    getActivity().setResult(event.getResultCode());
                }

            }
            getActivity().finish();
        }
        //启动activity事件
        else if (data instanceof StartActivityEvent) {
            StartActivityEvent event = (StartActivityEvent) data;
            if (event.getClz() != null) {
                startActivity(event.getClz());
            } else {
                startActivity(event.getIntent());
                if (event.isFinishActivity()) {
                    getActivity().finish();
                }
            }
        }
    }

    @Override
    public LifecycleOwner getLifecycleOwner() {
        return this;
    }

    @Override
    public void showLoading() {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showLoading();
        }
    }

    @Override
    public void showLoading(boolean isCanBack) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showLoading(isCanBack);
        }
    }

    @Override
    public void showLoading(String loadingMsg) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showLoading(loadingMsg);
        }
    }

    @Override
    public void showLoading(int loadingMsgId) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showLoading(loadingMsgId);
        }
    }

    @Override
    public void showLoading(String loadingMsg, boolean isCanBack) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showLoading(loadingMsg, isCanBack);
        }
    }

    @Override
    public void hideLoading() {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).hideLoading();
        }
    }

    @Override
    public void showToast(String msg) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).showToast(msg);
        }
    }

    @Override
    public void startActivity(Class clz) {
        if (parentActivity instanceof BaseView) {
            ((BaseView) parentActivity).startActivity(clz);
        }
    }

    @Override
    public Context getContext() {
        return parentActivity;
    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        if (parentActivity != null) {
            InputMethodManager imm = (InputMethodManager) parentActivity.getSystemService(INPUT_METHOD_SERVICE);
            View view = parentActivity.getCurrentFocus();
            if (imm != null && view != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }
}
